import { ref, watch, reactive, toRefs } from 'vue';
import event from '../tools/event';
import '../style/input.css';

export default {
  name: 'My-Input',
  props: {
    value: {
      type: [String, Number],
      default: '',
    },
    addStyle: {
      type: Object,
      default: () => ({}),
    },
    isReadonly: {
      type: Boolean,
      default: false,
    },
    parentColumnId: {
      type: [String, Number],
      default: '',
    },
    editPropName: {
      type: String,
      default: '',
    },
    componentName: {
      type: String,
      default: '',
    },
  },
  setup(props) {
    const newValue = ref('');

    watch(
      () => props.value,
      (val) => {
        const v = Object.is(val, NaN) ? '0' : val;
        newValue.value = v;
      },
      { immediate: true },
    );

    watch(newValue, (val) => {
      if (props.isReadonly && Object.is(Number(val), NaN)) {
        return;
      }

      const data = {
        value: val,
        prop: props.editPropName,
        parentColumnId: props.parentColumnId,
      };

      try {
        event.emit(`inputChange-${props.componentName}`, data);
      } catch (err) {
        // console.error("error", data, val, err);
      }
    });

    return {
      ...toRefs(props),
      newValue,
    };
  },
  render() {
    return (
      <div>
        <div class="el-input">
          <input
            type="text"
            disabled={this.isReadonly}
            v-model={this.newValue}
            parentColumnId={this.parentColumnId}
            autocomplete="off"
            class="el-input__inner__1"
            readonly={this.isReadonly}
            style={this.addStyle}
          />
        </div>
      </div>
    );
  },
};
